import { getLocalHistories } from '@/utils/storage';
import { uniq } from 'lodash';

const initialState = {
  suggest: [] as string[],
  histories: getLocalHistories(),
  // 此处要加断言,不然会报错
  resultsData: {
    per_page: 1,
    page: 10,
    results: [] as resultType[],
    total_count: 0,
  },
};
export type resultType = {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: {
    type: number;
    images: string[];
  };
  like_count: number;
  collect_count: number;
};
type actionType =
  | { type: 'search/saveSuggest'; payload: string[] }
  | { type: 'search/saveHistories'; payload: string[] }
  | { type: 'search/clearHistories' }
  | { type: 'search/saveResults'; payload: typeof initialState.resultsData }
  | { type: 'search/updateResults'; payload: typeof initialState.resultsData };

// eslint-disable-next-line import/no-anonymous-default-export
export default (
  state = initialState,
  action: actionType
): typeof initialState => {
  switch (action.type) {
    case 'search/saveSuggest':
      return {
        ...state,
        // 脏数据会返回null
        suggest: action.payload.filter((item) => !!item),
      };
    case 'search/saveHistories':
      return {
        ...state,
        // histories: [...(new Set([...state.histories, action.payload]) as any)],
        // 限制搜索记录只有10条
        histories: uniq([...state.histories, action.payload] as string[]).slice(
          0,
          10
        ),
      };
    case 'search/clearHistories':
      return {
        ...state,
        histories: [],
      };
    case 'search/saveResults':
      return {
        ...state,
        resultsData: {
          total_count: action.payload.total_count,
          per_page: action.payload.per_page,
          page: action.payload.page,
          results: action.payload.results,
        },
      };
    case 'search/updateResults':
      return {
        ...state,
        resultsData: {
          total_count: action.payload.total_count,
          per_page: action.payload.per_page,
          page: action.payload.page,
          results:
            [...state.resultsData.results, ...action.payload.results] || [],
        },
      };
    default:
      return state;
  }
};
